package com.jinlia.show.common.core.utils;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class WeChatPayUtil {
    // 生成随机字符串
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    // 生成时间戳
    public static String generateTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    // 生成签名
    public static String generateSignature(Map<String, String> params, String apiKey) throws NoSuchAlgorithmException {
        // 参数排序
        TreeMap<String, String> sortedMap = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = sortedMap.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            if (entry.getValue() != null && !"".equals(entry.getValue()) && !"sign".equals(entry.getKey()) && !"key".equals(entry.getKey())) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        sb.append("key=").append(apiKey);
        return generateMD5Sign(sb.toString()).toUpperCase();
    }

    // 生成MD5签名
    public static String generateMD5Sign(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(String.format("%02x", item));
        }
        return sb.toString();
    }

    // 生成HMAC-SHA256签名（例如用于生成支付预支付交易会话标识）
    public static String generateHMACSHA256Sign(String data, String apiKey) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Hex.encodeHexString(array).toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        // 示例参数，请根据实际情况填写
        Map<String, String> params = new TreeMap<>();
        params.put("appid", "your_appid");
        params.put("mch_id", "your_mch_id");
        params.put("nonce_str", generateNonceStr());
        params.put("body", "Test Order");
        params.put("out_trade_no", "order_no_" + System.currentTimeMillis());
        params.put("total_fee", "1"); // 单位为分
        params.put("spbill_create_ip", "123.12.12.123"); // 终端IP
        params.put("notify_url", "https://your_notify_url.com");
        params.put("trade_type", "JSAPI");
        params.put("openid", "user_openid");

        String apiKey = "your_api_key";
        String sign = generateSignature(params, apiKey);

        System.out.println("Generated Sign: " + sign);

        // 可以在这里将params和sign传递给微信服务器进行支付请求
    }
}
